import React, { useEffect } from 'react';
import { Button, Space } from 'antd';
import {
  ModalForm,
  ProFormText,
  ProFormDigit,
} from '@ant-design/pro-form';
import ProCard from '@ant-design/pro-card';
import styles from '../index.less';
import { ItemInfoProps } from '@/pages/market/Item';
import { isAddress, isHexString } from 'ethers/lib/utils';
import moment from 'moment';

const OperationCard: React.FC<ItemInfoProps> = (props) => {
  const { initialState,item } = props;
  const {
    provider,
    contracts: { fileStorageContract, saleContract,auctionContract,licenseContract },
    currentAccount,
  } = initialState;

  // 非确权成功状态返回空 或 非作品拥有者返回空
  if (item.status !== 1 || currentAccount?.address !== item.ownerAddress) {
    return <></>;
  }

  const fixPriceSaleForm = (
    <ModalForm<{
      price: number;
      buyer: string;
    }>
      title="设置价格"
      trigger={<Button type="primary">定价出售</Button>}
      onFinish={async (values) => {
        if (!values.buyer || values.buyer === '') {
          values.buyer = '0x0000000000000000000000000000000000000000';
        }
        try {
          const signer = await provider.getSigner();
          const overrides = {
            from: await signer.getAddress(),
            gasPrice: await provider.getGasPrice(),
            gasLimit: 500000,
            nonce: await signer.getTransactionCount(),
          };
          await marketContract.callStatic.createSale(
            fileStorage.tokenID,
            values.price,
            values.buyer,
            overrides,
          );
          const tx = await marketContract
            .connect(signer)
            .createSale(
              fileStorage.tokenID,
              values.price,
              values.buyer,
              overrides,
            );
          await tx.wait();
          window.location.reload();
        } catch (e) {
          console.error(e);
        }
        return true;
      }}
    >
      <ProFormDigit
        name="price"
        label="定价"
        placeholder="金额"
        rules={[
          {
            required: true,
            message: '请输入定价',
          },
        ]}
        fieldProps={{}}
      />
      <ProFormText
        name="buyer"
        label={'指定用户'}
        placeholder={'用户账户'}
        rules={[
          {
            validator: (_, value) =>
              isAddress(value) || !value
                ? Promise.resolve()
                : Promise.reject(new Error('地址格式错误')),
          },
        ]}
      />
    </ModalForm>
  );

  const auctionForm = (
    <ModalForm
      title="设置价格"
      trigger={<Button type="primary">拍卖出售</Button>}
      onFinish={async (values) => {
        values.duration = moment.duration(values.duration, 'hours').asSeconds();
        try {
          const signer = await provider.getSigner();
          const gasPrice = await provider.getGasPrice();
          const overrides = {
            from: await signer.getAddress(),
            gasPrice: gasPrice.toNumber(),
            gasLimit: 500000,
            nonce: await signer.getTransactionCount(),
          };
          // 预执行合约
          await marketContract.callStatic.createAuction(
            fileStorage.tokenID,
            values.price,
            values.duration,
            overrides,
          );
          // 实际执行合约
          const tx = await marketContract
            .connect(signer)
            .createAuction(
              fileStorage.tokenID,
              values.price,
              values.duration,
              overrides,
            );
          await tx.wait();
          window.location.reload();
        } catch (e) {
          console.error(e);
        }
        return true;
      }}
    >
      <ProFormText
        name="price"
        label="起拍价"
        placeholder="金额"
        rules={[
          {
            required: true,
          },
        ]}
      />
      <ProFormDigit
        name="duration"
        label="持续时间"
        placeholder="持续时间"
        rules={[
          {
            required: true,
          },
        ]}
      />
    </ModalForm>
  );

  const licenseForm = (
    <ModalForm
      title="设置价格"
      trigger={<Button type="primary">授权设置</Button>}
    >
      <ProFormText
        name="price"
        label="定价"
        placeholder="金额"
        rules={[
          {
            required: true,
            message: '请输入定价',
          },
        ]}
      />
      <ProFormDigit label="授权个数" name="count" min={1} max={10} />
    </ModalForm>
  );

  // const approvalForm = (
  //   <ModalForm<{
  //     tokenId: number;
  //     contractAddress: string;
  //   }>
  //     title="交易授权"
  //     trigger={<Button type="primary">启用交易</Button>}
  //     onFinish={async (values) => {
  //       try {
  //         const signer = await provider.getSigner();
  //         const overrides = {
  //           from: await signer.getAddress(),
  //           gasPrice: await provider.getGasPrice(),
  //           gasLimit: 500000,
  //           nonce: await signer.getTransactionCount(),
  //         };
  //
  //         //           const domain = {
  //         //             name: 'Ether Mail',
  //         //             version: '1',
  //         //             chainId: 9999,
  //         //             verifyingContract: '0xa50D5a05A0f6444936e209742d95BF11A9b2E2C9'
  //         //           };
  //         //
  //         // // The named list of all type definitions
  //         //           const types = {
  //         //             Person: [
  //         //               { name: 'name', type: 'string' },
  //         //               { name: 'wallet', type: 'address' }
  //         //             ],
  //         //             Mail: [
  //         //               { name: 'from', type: 'Person' },
  //         //               { name: 'to', type: 'Person' },
  //         //               { name: 'contents', type: 'string' }
  //         //             ]
  //         //           };
  //         //
  //         // // The data to sign
  //         //           const value = {
  //         //             from: {
  //         //               name: 'gan',
  //         //               wallet: '0x4671BbA62a82D9c7C88B13F02D1cCd7e1fA2D1d8'
  //         //             },
  //         //             to: {
  //         //               name: 'lala',
  //         //               wallet: '0x4671BbA62a82D9c7C88B13F02D1cCd7e1fA2D1d8'
  //         //             },
  //         //             contents: '123'
  //         //           };
  //         //
  //         //           const signature = await signer._signTypedData(domain, types, value);
  //         //           console.log(signature)
  //
  //         // console.log("address:"+await signer.getAddress())
  //         // const hashMessage = ethers.utils.hashMessage('123');
  //         // console.log("hashMessage:"+hashMessage)
  //         // const signature = await signer.signMessage(item.fileHash);
  //         // console.log("recoverAddress"+ethers.utils.recoverAddress(hashMessage,signature))
  //         // console.log(ethers.utils.isBytes( item.fileHash ))
  //         // console.log(await testContract.callStatic.testRecover(item.fileHash,signature,overrides));
  //
  //         // 预执行合约
  //         await fileStorageContract.callStatic.approve(
  //           values.contractAddress,
  //           values.tokenId,
  //           overrides,
  //         );
  //         // 实际执行合约
  //         const tx = await fileStorageContract
  //           .connect(signer)
  //           .approve(values.contractAddress, values.tokenId, overrides);
  //         await tx.wait();
  //         window.location.reload();
  //       } catch (e) {
  //         console.error(e);
  //       }
  //       return true;
  //     }}
  //   >
  //     <ProFormText
  //       name="tokenId"
  //       label="tokenId"
  //       disabled
  //       initialValue={fileStorage.tokenID}
  //       rules={[
  //         {
  //           required: true,
  //         },
  //       ]}
  //     />
  //     <ProFormSelect
  //       name="contractAddress"
  //       label="交易合约地址"
  //       valueEnum={{
  //         '0xdB7d6AB1f17c6b31909aE466702703dAEf9269Cf':
  //           '定价交易',
  //         '0x537e697c7AB75A26f9ECF0Ce810e3154dFcaaf44':
  //           '拍卖交易',
  //         '0x880EC53Af800b5Cd051531672EF4fc4De233bD5d':
  //           '授权交易',
  //       }}
  //       rules={[
  //         {
  //           required: true,
  //         },
  //       ]}
  //     />
  //   </ModalForm>
  // );

  // 判断是否已经向交易合约授权 显示不同的操作按钮
  if (!item.approvalTxHash || !isHexString(item.approvalTxHash)) {
    return (
      <ProCard className={styles.itemCard} headerBordered bordered title="操作">
        <Space>{approvalForm}</Space>
      </ProCard>
    );
  } else {
    return (
      <ProCard className={styles.itemCard} headerBordered bordered title="操作">
        <Space>
          {fixPriceSaleForm}
          {auctionForm}
          {licenseForm}
        </Space>
      </ProCard>
    );
  }
};

export default OperationCard;
